#!/bin/sh

#
# Test the MBR creation ability of fwup
#

. "$(cd "$(dirname "$0")" && pwd)/common.sh"

cat >$CONFIG <<EOF
# Numbers don't matter for the test so long as the MBR is right
define(UBOOT_OFFSET, 2048)
define(UBOOT_WRITE_OFFSET, 2056) # Skip 8 blocks (4K) before writing the U-Boot image
define(UBOOT_ENV_1_OFFSET, 6144)
define(UBOOT_ENV_2_OFFSET, 12288)
define(ROOTFS_A_PART_OFFSET, 14336)
define(ROOTFS_A_PART_COUNT, 289044)

mbr mbr-a {
    include-osip = true
    osip-major = 1
    osip-minor = 0
    osip-num-pointers = 1

    osii 0 {
        os-major = 0
        os-minor = 0
        start-block-offset = \${UBOOT_OFFSET}
        ddr-load-address = 0x01100000
        entry-point = 0x01101000
        image-size-blocks = 0x0000c000
        attribute = 0x0f
    }

    partition 0 {
        block-offset = \${ROOTFS_A_PART_OFFSET}
        block-count = \${ROOTFS_A_PART_COUNT}
        type = 0x83 # Linux
    }
}
task complete {
	on-init {
                mbr_write(mbr-a)
        }
}
EOF

# Create the expected by running base64 on the expected binary image.
base64_decode >$WORK/expected.img <<EOF
JE9TJAAAAfIBATgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAEAEAEBABAMAAAA8AAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4yQAg+EjEgA4
AAAUaQQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVao=
EOF

# Create the firmware file, then "burn it"
$FWUP_CREATE -c -f $CONFIG -o $FWFILE
$FWUP_APPLY -a -d $IMGFILE -i $FWFILE -t complete

# The firmware file is equivalent to the following dd call
cmp_bytes 512 $WORK/expected.img $IMGFILE

# Check that the verify logic works on this file
$FWUP_VERIFY -V -i $FWFILE
